﻿using Microsoft.AspNetCore.Mvc;
using Singer.BackgroundJob.RabbitMQ.BackgroundJobLogs;
using Singer.BackgroundJob.RabbitMQ.Contracts;
using Singer.UnitTestWeb.BackgroundJobs.JobArgs;

namespace Singer.UnitTestWeb.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BackgroundJobController : ControllerBase
    {
        IBackgroundJobTrigger _backgroundJobTrigger;
        IBackgroundJobLogRepository _backgroundJobLogRepository;
        IBackgroundJobLogDetailRepository _backgroundJobLogDetailRepository;

        public BackgroundJobController(IBackgroundJobTrigger backgroundJobTrigger, IBackgroundJobLogRepository backgroundJobLogRepository, IBackgroundJobLogDetailRepository backgroundJobLogDetailRepository)
        {
            _backgroundJobTrigger = backgroundJobTrigger;
            _backgroundJobLogRepository = backgroundJobLogRepository;
            _backgroundJobLogDetailRepository = backgroundJobLogDetailRepository;
        }

        [HttpPost]
        public Task<string> PublishAuthorJob(AuthorJobArgs args)
        {
            return _backgroundJobTrigger.PublishAsync(args);
        }

        [HttpPost]
        public Task<string> PublishBookJob(BookJobArgs args)
        {
            return _backgroundJobTrigger.PublishAsync(args);
        }

        [HttpGet]
        public Task CancelJob(string jobLogId)
        {
            return _backgroundJobTrigger.CancellingAsync(jobLogId);
        }

        [HttpGet]
        public Task RestartJob(string jobLogId)
        {
            return _backgroundJobTrigger.RestartingAsync(jobLogId);
        }

        [HttpGet]
        public Task<List<BackgroundJobLog>> GetJobList()
        {
            return _backgroundJobLogRepository.Select.OrderByDescending(x => x.CreateTime).ToListAsync();
        }

        [HttpGet]
        public Task<List<BackgroundJobLogDetail>> GetJobLogDetailList(string jobLogId)
        {
            return _backgroundJobLogDetailRepository.Where(x => x.LogId == jobLogId).OrderByDescending(x => x.CreateTime).ToListAsync();
        }
    }
}
